package com.droidblackbox.history;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.droidblackbox.R;
import com.droidblackbox.manager.FileManager;
import com.droidblackbox.manager.SystemManager;

public class History extends Activity implements OnClickListener {
	private static final int ID_PLAYER_LAYOUT = 0x1010001;
	private static final int ID_MAPVIEW_LAYOUT = 0x1010011;
	private static final int ID_DELETE_LAYOUT = 0x1010111;

	private File[] recordList = null;

	private List<FileListInfo> list = null;
	private ListView listView = null;
	private HistoryAdaptor<FileListInfo> arrayAdapter = null;

	private LinearLayout playerLayout = null;
	private LinearLayout buttonLayout = null;
	private LinearLayout listLayout = null;
	private LinearLayout mapViewLayout = null;
	private ImageView deleteView = null;

	private Animation animation = null;

	private String selectFile = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.history);

		new AddAsyncTask().execute();

	}

	private static final int DIALOG_PROGRESS = 1;
	private static final int MAX_PROGRESS = 0x70;
	private ProgressDialog progressDialog = null;

	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_PROGRESS:

			progressDialog = new ProgressDialog(History.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setTitle("DrodiBlackBox");
			progressDialog.setMessage("Loading..... Please wait..");
			progressDialog.setCancelable(false);
			progressDialog.setMax(MAX_PROGRESS); // Max값 100
			return progressDialog;

		}
		return null;
	}

	class AddAsyncTask extends AsyncTask<Void, Integer, Void> {

		@Override
		protected void onPreExecute() {
			initCompoment();

			showDialog(DIALOG_PROGRESS);

			progressDialog.setProgress(0);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... unused) {

			runOnUiThread(new Runnable() {

				public void run() {

					try {
						openFiles();
						setListView();
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			});
			publishProgress(MAX_PROGRESS);
			return (null);
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			progressDialog.setProgress(progress[0]);
		}

		@Override
		protected void onPostExecute(Void unused) {
			dismissDialog(DIALOG_PROGRESS);
			progressDialog.dismiss();

		}

		protected void onCancelled() {
			super.onCancelled();
		}
	}

	private void initCompoment() {
		playerLayout = (LinearLayout) findViewById(R.id.historyPlayerLayout);
		buttonLayout = (LinearLayout) findViewById(R.id.historyButtonLayout);
		listLayout = (LinearLayout) findViewById(R.id.historyListLayout);
		mapViewLayout = (LinearLayout) findViewById(R.id.historyMapLayout);

		animation = AnimationUtils.loadAnimation(this, R.anim.history_show);

		buttonLayout.setVisibility(View.GONE);
		playerLayout.setId(ID_PLAYER_LAYOUT);
		mapViewLayout.setId(ID_MAPVIEW_LAYOUT);

		playerLayout.setOnClickListener(this);
		mapViewLayout.setOnClickListener(this);

		deleteView = (ImageView) findViewById(R.id.deleteView);
		deleteView.setId(ID_DELETE_LAYOUT);
		deleteView.setOnClickListener(this);
	}

	private void setListView() throws Exception {
		listView = (ListView) findViewById(R.id.historyListView);

		arrayAdapter = new HistoryAdaptor<FileListInfo>(this,
				R.layout.history_listrow, list);

		arrayAdapter.notifyDataSetChanged();
		listView.setAdapter(arrayAdapter);
		listView.refreshDrawableState();

		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				if (list.get(position).isChecked() == true) {
					list.get(position).setChecked(false);
				} else {
					list.get(position).setChecked(true);
				}
				arrayAdapter.notifyDataSetChanged();

				if (getSelectCount() == 0) {
					SystemManager.getInstance().showToast(
							getApplicationContext(),
							getResources().getString(
									R.string.history_file_no_check));

					buttonLayout.setVisibility(View.INVISIBLE);
					buttonLayout.setVisibility(View.GONE);

					final int fillParent = LinearLayout.LayoutParams.FILL_PARENT;
					listLayout.setLayoutParams(new LinearLayout.LayoutParams(
							fillParent, fillParent));
					return;
				} else {
					buttonLayout.setVisibility(View.VISIBLE);
					SystemManager.getInstance().showToast(
							getApplicationContext(),
							getResources().getString(
									R.string.history_file_check)
									+ getSelectCount());

					if (buttonLayout.isShown() == false)
						buttonLayout.startAnimation(animation);

				}
			}
		});
	}

	private void openFiles() {
		list = new ArrayList<FileListInfo>();

		File file = null;
		try {
			file = FileManager.getFile(FileManager.FOLDER_RECORD);
		} catch (IOException e) {
			e.printStackTrace();
		}
		recordList = file.listFiles();

		for (File f : recordList) {
			if (f.isFile()) {
				if (f.getName().equals(FileManager.TEMP) == false) {
					FileListInfo fileListInfo = new FileListInfo();
					fileListInfo.setFile(f);
					fileListInfo.setName(f.getName());
					fileListInfo.setChecked(false);
					list.add(fileListInfo);
				}
			}
		}
	}

	private int getSelectCount() {
		int checkedCount = 0;

		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).isChecked()) {
				selectFile = recordList[i].getName();
				checkedCount++;
			}
		}

		return checkedCount;
	}

	public void onClick(View v) {

		if (getSelectCount() == 0)
			return;

		Intent intent = null;
		switch (v.getId()) {
		case ID_PLAYER_LAYOUT:
			if (getSelectCount() > 1)
				return;

			intent = null;
			intent = new Intent(History.this, HistoryRecordPlayer.class);
			intent.putExtra(FileManager.SELECT_FILE, selectFile);
			startActivity(intent);
			break;
		case ID_MAPVIEW_LAYOUT:
			if (getSelectCount() > 1)
				return;

			intent = null;
			intent = new Intent(History.this, HistoryMapViewPlayer.class);
			intent.putExtra(FileManager.SELECT_FILE, selectFile);
			startActivity(intent);
			break;
		case ID_DELETE_LAYOUT:

			showFileDeleteAlert();

			break;
		}
	}

	private void showFileDeleteAlert() {
		final String alertTitle = getString(R.string.file_alert_title);
		final String alertMessage = getString(R.string.file_alert_message);
		final String alertYes = getString(R.string.file_alert_yes);
		final String alertNo = getString(R.string.file_alert_no);

		new AlertDialog.Builder(this)
				.setTitle(alertTitle)
				.setMessage(alertMessage)
				.setPositiveButton(alertYes,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								deleteFiles();

							}
						}).setNegativeButton(alertNo, null).show();
	}

	private void deleteFiles() {
		boolean isDelete = false;
		try {
			for (int i = 0; i < list.size(); i++) {

				FileListInfo info = list.get(i);
				if (info.isChecked()) {
					isDelete = FileManager.delete(recordList[i]);
				}
			}

			openFiles();
			setListView();

			if (isDelete == true)
				SystemManager.getInstance().showToast(getApplicationContext(),
						"File Delete");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
